package com.example.demo;

import com.example.demo.base.ResultEntity;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;


/**
 * @Author: 喻晓涵
 * @CreateTime: 2025-08-03
 * @Description: 1
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/ai")
public class AiPort {
    @Autowired
    ChatClient.Builder chatClientBuilder;

    @GetMapping
    public ChatCompletion qry() {




        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey("sk-7517c06221974628bd8b2ea6f01bf2bc")
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                .addUserMessage("你是谁")
                .model("qwen-turbo")
                .build();



        try {
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            System.out.println(chatCompletion.choices().get(0).message());
            return chatCompletion;
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }



        return null;
    }

    @PostMapping("/qryAli")
    public ChatCompletion qryAli(String q) {

        ChatClient chatClient = this.chatClientBuilder.build();
        ResultEntity resultEntity = chatClient.prompt()
                .user("你是谁")
                .call()
                .entity(ResultEntity.class);
        System.out.println(resultEntity);
        return null;
    }

    @PostMapping("/qryAliFlux")
    public ChatCompletion qryAliFlux(String q) {
        ChatClient chatClient = this.chatClientBuilder.defaultSystem("""
                你是一名ai出题助手，能够智能化根据用户文本中的知识点来生成相关题目,包含，单选、多选、判断题，回复的题目第一批单选题，第二批多选题，第三批判断题，然后以一定的格式返回给系统封装成实体入库
               
                ###回复格式
                1.
                
                **特别注意：**
                -出的题目要有
                
                当前服务用户：
                姓名：{name}，年龄{age}
                
                """
        ).build();
         Flux<String> result = chatClient.prompt()
                 .system(p -> p.param("name", "小王").param("age", "18"))
                .user("你是谁")
                .stream()
                 .content();
         result.toIterable().forEach(s -> System.out.println(s));
        return null;
    }
}
